package com.qf.j2205.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName MybitesUtil
 * @Description TODO
 * @Author Windy
 * @Date 2022/8/12 11:34
 * @Version 1.0
 **/
public class MybitesUtil {
    private static  SqlSessionFactory ssf =null;
    private static ThreadLocal<SqlSession> ts=new ThreadLocal<>();

    //读取配置文件
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybits_config.xml");
            ssf = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //获取连接
    public static SqlSession getSession(){
        SqlSession ss=ts.get();
        if (ss == null) {
            ss = ssf.openSession();
            ts.set(ss);
        }
        return ss;
    }
    //关闭连接
    public static void closeAll(){
        SqlSession ss = ts.get();
        if (ss != null) {
            ss.close();
        }
        ts.remove();
    }

    //提交事务
    public static void commitWork(){
        SqlSession ss = ts.get();
        if (ss != null) {
            ss.commit();
        }
    }

    //回滚事务
    public static void rollbackWork() {
        SqlSession ss = ts.get();
        if (ss != null) {
            ss.rollback();
        }
    }
}
